package com.xsomnus.java_basic.juc;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author @叶小夏
 * @since 2019/7/29 0029 17:41
 * - 才需学也,学需静也/非淡泊无以明志，非宁静无以致远
 */
public class CountdownLatchTest {

    private final static OkHttpClient okHttpClient = new OkHttpClient();

    private static List<String> visitUrls = Arrays.asList("http://www.baidu.com", "http://v.qq.com", "http://ifeve.com/juc-aqs-reentrantlock/", "http://ifeve.com/understand-condition/");

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(visitUrls.size());
        long start = System.currentTimeMillis();
        visitUrls.forEach(s -> new Thread(new CheckURL(s, countDownLatch)).start());
        countDownLatch.await();
        long end = System.currentTimeMillis();

        System.out.println("with thread ---" + (end - start) + "毫秒");

        start = System.currentTimeMillis();
        visitUrls.forEach(url -> {
            final Call call = okHttpClient.newCall(new Request.Builder().url(url).build());
            try {
                final Response execute = call.execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        end = System.currentTimeMillis();

        System.out.println("no thread ---" + (end - start) + "毫秒");
    }

    private static class CheckURL implements Runnable {

        private String url;

        private CountDownLatch countDownLatch;

        CheckURL(String url, CountDownLatch countDownLatch) {
            this.url = url;
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            final Call call = okHttpClient.newCall(
                    new Request.Builder().url(url).build()
            );
            final Response response;
            try {
                response = call.execute();
                final String string = response.body().string();
                countDownLatch.countDown();
                //System.out.println(string);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
